<template>
  <el-form class="query-container" ref="queryFormRef" :model="queryParams" :inline="true" @submit.native.prevent>
    <el-form-item>
      <el-date-picker v-model="queryParam.assess" type="date" placeholder="选择日期">
      </el-date-picker>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="query">搜索</el-button>
      <el-button @click="resetQuery">重置</el-button>
    </el-form-item>
  </el-form>

  <div class="inner-container">
    <el-row :gutter="10" style="margin-bottom:8px">
      <el-col :span="1.5">
        <el-button type="primary" plain @click="addIndicators">新增</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="tableData" @selection-change="handleSelectionChange">
      <el-table-column prop="assess" label="考核时间" min-width="120"></el-table-column>
      <el-table-column prop="dept" label="部门" show-overflow-tooltip></el-table-column>
      <el-table-column prop="staff" label="员工" show-overflow-tooltip></el-table-column>
      <el-table-column prop="status" label="业务类型" :formatter="(row, column, cellValue, index) => {
        if(cellValue == 1){
          cellValue = '个人订单/月'
        }if(cellValue == 2){
          cellValue = '个人产值/月'
        }if(cellValue == 3){
          cellValue = '个人客户/月'
        }
        return cellValue;
      }"></el-table-column>
      <el-table-column prop="orderIndex" label="订单指标"></el-table-column>
      <el-table-column prop="costIndex" label="产值指标"></el-table-column>
      <el-table-column prop="userIndex" label="客户指标"></el-table-column>
      <el-table-column prop="progress" label="进度"></el-table-column>
      <el-table-column prop="name" label="创建者" min-width="100"></el-table-column>
      <el-table-column prop="createTime" label="创建时间"></el-table-column>
      <el-table-column label="操作" align="center" fixed="right" width="160">
        <template #default="scope">
          <el-button type="primary" link @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>




    <el-dialog :title="'新增业务指标'" v-model="dialogVisible" style="width:1000px;padding:40px;"
               :before-close="handleClose" append-to-body>
      <el-form label-width="80px" label-position="top" :model="addBusiness"  :rules="formRules" ref="addBusinessRef">
        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="考核时间" prop="assess">
              <el-date-picker
                  v-model="addBusiness.assess"
                  type="date"
                  placeholder="请选择日期"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="30">
          <el-col :span="7">
            <el-form-item label="部门" prop="deptId">
              <el-select placeholder="请选择部门" v-model="addBusiness.deptId" @change="getStaff">
                <el-option v-for="i in deptList" :value="i.id" :label="i.name" >{{i.name}}</el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="30">
          <el-col :span="7">
            <el-form-item label="员工" prop="staffId">
              <el-select placeholder="请选择员工" v-model="addBusiness.staffId">
                <el-option v-for="i in staffList" :value="i.id" :label="i.name">{{i.name}}</el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="30">
          <el-col :span="7">
            <el-form-item label="订单指标" prop="orderIndex">
              <el-input v-model="addBusiness.orderIndex" placeholder="请输入订单指标" ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="30">
          <el-col :span="7">
            <el-form-item label="客户指标" prop="userIndex">
              <el-input v-model="addBusiness.userIndex" placeholder="请输入客户指标" ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="30">
          <el-col :span="7">
            <el-form-item label="产值指标" prop="costIndex">
              <el-input v-model="addBusiness.costIndex" placeholder="请输入产值指标" ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="saveBusiness">确定</el-button>
      </template>
    </el-dialog>


    <br>
    <el-pagination
        :total="total"
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
  </div>
</template>

<script setup>
import {onMounted, ref} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import {useRouter} from "vue-router"
import request from "@/utils/request";

const router = useRouter();

//----------------------------------------------------
const addBusinessRef = ref();
const addBusiness = ref({
  assess: '',
  deptId: '',
  staffId: '',
  orderIndex: '',
  userIndex: '',
  costIndex: ''
});
const deptList = ref([]);
const staffList = ref([]);
const getDept = () => {
  request.get('/api/crm/assess/loadDept').then(res => {
    deptList.value = res.data;
    console.log(deptList.value)
  })
}
const getStaff = () =>{
  addBusiness.value.staffId = '';
  staffList.value = [];
  request.get('/api/crm/assess/loadStaff',{
    params:{
      deptId:addBusiness.value.deptId
    }
  }).then(res=>{
    staffList.value = res.data;
    console.log(res.data)
    console.log(staffList.value)
  })
}
const saveBusiness = async () => {
  try {
    await addBusinessRef.value.validate();
    await request.post('/api/crm/assess/save', addBusiness.value).then(res => {
      ElMessage.success('新增成功')
      handleClose();
      listData();
    })
  } catch (error) {
    ElMessage.error('至少填写一个指标')
  }
}

const validateAtLeastOne = (rule, value, callback) => {
  if (addBusiness.value.orderIndex || addBusiness.value.userIndex || addBusiness.value.costIndex) {
    console.log("已通过表单验证")
    return  callback();
  } else {
    new Error('至少填写一个指标');
  }
};

const formRules = {
  assess: [
    {required: true, message: '请选择考核时间'},
  ],
  deptId: [
    {required: true, message: '请选择部门'},
  ],
  staffId: [
    {required: true, message: '请选择员工'},
  ],
  orderIndex: [
    {pattern: /^[0-9]+$/, message: '只能输入数字'},
    { validator: validateAtLeastOne(), trigger: 'blur' },
  ],
  userIndex: [
    {pattern: /^[0-9]+$/, message: '只能输入数字'},
    { validator: validateAtLeastOne(), trigger: 'blur' },
  ],
  costIndex: [
    {pattern: /^[0-9]+$/, message: '只能输入数字'},
    { validator: validateAtLeastOne(), trigger: 'blur' },
  ],
}
// --------------------------------------------------
const dialogVisible = ref(false)
const addIndicators = () => {
  dialogVisible.value = true;
}
const handleClose = () => {
  dialogVisible.value = false;
  addBusiness.value = {
    assess: '',
    deptId: '',
    staffId: '',
    orderIndex: '',
    userIndex: '',
    costIndex: ''
  }
}
//------------------------------------------------
const queryParam = ref({
  assess: ''
});
const query = () => {
  console.log(queryParam.value)
  request.post('/api/crm/assess/select',queryParam.value).then(res=>{
    total.value = res.data.total;
    tableData.value = res.data.list;
  })
}
const resetQuery = () => {
  queryFormRef.value.resetFields();
  queryParam.value = {
    assess: ''
  }
  listData();
}








// --------------------------------------------------
const loading = ref(false)
const queryFormRef = ref()
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  status: undefined,
  source: undefined,
  field: 'number',
  keyword: undefined,
  deptId: undefined
})
const total = ref(0)
const tableData = ref([])
const selectedIds = ref([])


const listData = () => {
  request.get('/api/crm/assess/load', {
    params: queryParams.value
  }).then(res => {
    total.value = res.data.total
    tableData.value = res.data.list
    console.log(res.data)
    loading.value = false
  })
  tableData.value = [
    {
      id: 602,
      name: '李先生',
      contactPhone: '13456789012',
      propertyName: '西钓鱼台',
      propertyAddr: '',
      source: '家博会',
      designer: '',
      manager: '',
      followTime: '2019.8.3',
      followNum: 2,
      reserveTime: '2019.8.5',
      merchandiser: 'xxx',
      status: '未订单客户 一客到店',
      createBy: 'admin',
      createTime: '2024-07-08 17:28:00'
    }
  ]
  total.value = 99
}

const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id)
}

const handleQuery = () => {
  queryParams.value.pageNum = 1
  listData()
}



const handleCurrentChange = (val) => {
  queryParams.value.pageNum = val
  listData()
}

const handleSizeChange = (val) => {
  queryParams.value.pageSize = val
  listData()
}

const handleDelete = (id) => {
  ElMessageBox.confirm('确定删除吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    request.get('/api/crm/assess/delete', {
      params: {
        id: id
      }
    }).then(res => {
      ElMessage.success('删除成功');
      listData();
    })
  }).catch(() => {
    ElMessage.info('已取消删除');
  })
}

const goToEditView = (row) => {
  let id = row.id || selectedIds.value
  router.push({path: '/crm/customer/edit', query: {id: id}})
}

// --------------------------------------------------
onMounted(() => {
  listData();
  getDept();
})
</script>

<style scoped>

</style>
